package net.siufung.web.utils;

import cn.hutool.core.util.ObjectUtil;
import lombok.NoArgsConstructor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

import java.util.List;
import java.util.Objects;

/**
 * XssUtil
 *
 * @author 陈建峰
 * @date 2022/10/9 9:56 上午
 * @since V1.0.0
 */
@NoArgsConstructor
public class XssUtil {

    /**
     * 默认使用relaxed()
     */
    private Whitelist whiteList;

    /**
     * 配置过滤化参数,不对代码进行格式化
     */
    private Document.OutputSettings outputSettings;

    /**
     * 静态创建XssUtil方法
     * @param whiteList 白名单标签
     * @param pretty 是否格式化
     * @return XssUtil
     */
    public static XssUtil create(Whitelist whiteList, boolean pretty) {
        XssUtil xssUtil = new XssUtil();
        if (Objects.isNull(whiteList)) {
            xssUtil.whiteList = Whitelist.basicWithImages();
            xssUtil.whiteList.addAttributes(":all", "style");
        }
        xssUtil.outputSettings = new Document.OutputSettings().prettyPrint(pretty);
        return xssUtil;
    }

    /**
     * 静态创建XssUtil方法
     * @return XssUtil
     */
    public static XssUtil create() {
        return create(null, false);
    }

    /**
     * 静态创建XssUtil方法
     * @param whiteList 白名单标签
     * @return XssUtil
     */
    public static XssUtil create(Whitelist whiteList) {
        return create(whiteList, false);
    }

    /**
     * 静态创建XssUtil方法
     * @param excludeTags 例外的特定标签
     * @param includeTags 需要过滤的特定标签
     * @param pretty      是否格式化
     * @return XssUtil
     */
    public static XssUtil create(List<String> excludeTags, List<String> includeTags, boolean pretty) {
        XssUtil xssUtil = create(null, pretty);
        if (ObjectUtil.isNotEmpty(includeTags)) {
            String[] tags = includeTags.toArray(new String[0]);
            xssUtil.whiteList.removeTags(tags);
        }
        if (ObjectUtil.isNotEmpty(excludeTags)) {
            String[] tags = excludeTags.toArray(new String[0]);
            xssUtil.whiteList.addTags(tags);
        }
        return xssUtil;
    }

    /**
     * 静态创建XssUtil方法
     * @param excludeTags 例外的特定标签
     * @param includeTags 需要过滤的特定标签
     * @return XssUtil
     */
    public static XssUtil create(List<String> excludeTags, List<String> includeTags) {
        return create(includeTags, excludeTags, false);
    }

    /**
     * @param content 需要过滤内容
     * @return 过滤后的String
     */
    public String clean(String content) {
        return Jsoup.clean(content, "", this.whiteList, this.outputSettings);
    }

}
